package com.example.ks.servlet;

import com.example.ks.dao.impl.OrderDaoImpl;
import com.example.ks.dao.impl.UserDaoImpl;
import com.example.ks.entity.Order;
import com.example.ks.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin-index")
public class AdminIndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从会话中获取当前登录的管理员信息
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("user");
        
        if (admin == null || admin.getRole() != 1) {
            response.sendRedirect("login-register.jsp");
            return;
        }

        int adminId = admin.getId();
        try {
            OrderDaoImpl orderDao = new OrderDaoImpl();
            UserDaoImpl userDao = new UserDaoImpl();
            
            // 获取当前管理员的订单列表
            List<Order> orders = orderDao.getOrdersByAdminId(adminId);
            
            // 获取所有相关用户的用户名
            Map<Integer, String> userNames = new HashMap<>();
            // 添加当前管理员的用户名
            userNames.put(adminId, admin.getUsername());
            
            for (Order order : orders) {
                if (!userNames.containsKey(order.getUserId())) {
                    User normalUser = userDao.findById(order.getUserId());
                    if (normalUser != null) {
                        userNames.put(order.getUserId(), normalUser.getUsername());
                    }
                }
            }
            
            request.setAttribute("orders", orders);
            request.setAttribute("userNames", userNames);
            request.getRequestDispatcher("admin-index.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "获取订单列表失败：" + e.getMessage());
            request.getRequestDispatcher("admin-index.jsp").forward(request, response);
        }
    }
}
